<?php
/**
 * Project: ShopWorx- making your life easier
 *   
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * @Author Chris 
 * @File dbal.class.php
 * @Version 1.0.0
 * @Copyright 2008 Shopworx (c) 
 * @Year 2008
 * @access Private
 */
 
 /**
  * Database abstraction layer allows database connections to all sql engines.
  *
  *@package DBAL
  */

 define('DBAL_LOADED', true);
 
 Class DBAL {
	var $VERSION = "1.0.0";
	
	function DBAL($db_url)
	{
	  $this->db_url = $db_url;
	  
	  $this->connect();
	  
	  if ($this->connected == true)
	  {
		// set default mode for all resultsets
		$this->dbh->setFetchMode(DB_FETCHMODE_OBJECT);
	  }
	}
	
	function connect()
	{

	  //connect to the database
	  $status = $this->dbh = DB::connect($this->db_url);

	  if (DB::isError($status))
      {
		$this->connected = false;
		
		$this->error = $status->getMessage();
		return $this->error;
      } else {
		$this->connected = true;
      }
      return $this->connected;
	}
	
	function isConnected()
	{
		return $this->connected;
	}
	
	function disconnect()
	{

	  if (isset($this->dbh))
	  {
		$this->dbh->disconnect();
		return 1;
	  } else {
		return 0;
	  }
	}
	
	function query($statement)
	{
		$result = $this->dbh->query($statement);
		
		if (DB::isError($result))
		{
			$this->setError($result->getMessage());
			return null;
		} else {
			return $result;
		}
	}
	
	function setError($msg = null)
	{
		global $TABLE_DOES_NOT_EXIST, $TABLE_UNKNOWN_ERROR;
		
		$this->error = $msg;
		
		if (strpos($msg, 'no such table'))
		{
			$this->error_type = $TABLE_DOES_NOT_EXIST;
		} else {
			$this->error_type = $TABLE_UNKNOWN_ERROR;
		}
	}
	
	function isError()
	{
		return (!empty($this->error)) ? 1 : 0;
	}
	
	function getError()
	{
		return $this->error;
	}
	
	function quote($str)
	{
		return "'" . $str . "'";
	}
	
	function apiVersion()
	{
		return $this->VERSION;
	}
 }